package com.zone.service.controller;

import java.util.List;
import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zone.common.log.annotation.Log;
import com.zone.common.log.enums.BusinessType;
import com.zone.common.security.annotation.RequiresPermissions;
import com.zone.service.domain.MechanicalLock;
import com.zone.service.service.IMechanicalLockService;
import com.zone.common.core.web.controller.BaseController;
import com.zone.common.core.web.domain.AjaxResult;
import com.zone.common.core.utils.poi.ExcelUtil;
import com.zone.common.core.web.page.TableDataInfo;
import java.net.URLEncoder;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.core.io.ClassPathResource;
import com.zone.common.security.utils.SecurityUtils;
import java.io.InputStream;
import java.io.IOException;

/**
 * 钥匙组管理Controller
 * 
 * @author liuyang
 * @date 2025-10-23
 */
@RestController
@RequestMapping("/MechanicalLock")
public class MechanicalLockController extends BaseController
{
    @Autowired
    private IMechanicalLockService mechanicalLockService;

    /**
     * 查询钥匙组管理列表
     */
    @RequiresPermissions("service:MechanicalLock:list")
    @GetMapping("/list")
    public TableDataInfo list(MechanicalLock mechanicalLock)
    {
        startPage();
        List<MechanicalLock> list = mechanicalLockService.selectMechanicalLockList(mechanicalLock);
        return getDataTable(list);
    }

    /**
     * 导出钥匙组管理列表
     */
    @RequiresPermissions("service:MechanicalLock:export")
    @Log(title = "钥匙组管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MechanicalLock mechanicalLock)
    {
        List<MechanicalLock> list = mechanicalLockService.selectMechanicalLockList(mechanicalLock);
        ExcelUtil<MechanicalLock> util = new ExcelUtil<MechanicalLock>(MechanicalLock.class);
        util.exportExcel(response, list, "钥匙组管理数据");
    }

    /**
     * 获取钥匙组管理详细信息
     */
    @RequiresPermissions("service:MechanicalLock:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(mechanicalLockService.selectMechanicalLockById(id));
    }

    /**
     * 新增钥匙组管理
     */
    @RequiresPermissions("service:MechanicalLock:add")
    @Log(title = "钥匙组管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MechanicalLock mechanicalLock)
    {
        return toAjax(mechanicalLockService.insertMechanicalLock(mechanicalLock));
    }

    /**
     * 修改钥匙组管理
     */
    @RequiresPermissions("service:MechanicalLock:edit")
    @Log(title = "钥匙组管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MechanicalLock mechanicalLock)
    {
        return toAjax(mechanicalLockService.updateMechanicalLock(mechanicalLock));
    }

    /**
     * 删除钥匙组管理
     */
    @RequiresPermissions("service:MechanicalLock:remove")
    @Log(title = "钥匙组管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mechanicalLockService.deleteMechanicalLockByIds(ids));
    }
    
    /**
     * 导出钥匙组模板
     */
    @RequiresPermissions("service:MechanicalLock:export")
    @Log(title = "钥匙组管理", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        String templatePath = "templates/mechanicallock.xls";
        
        ClassPathResource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            logger.error("模板文件不存在: {}", templatePath);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        try {
            // 设置正确的 Content-Type 和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            
            // 安全编码文件名
            String fileName = URLEncoder.encode("钥匙组导入模板.xls", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 流式拷贝
            StreamUtils.copy(resource.getInputStream(), response.getOutputStream());
            response.flushBuffer();
            
        } catch (IOException e) {
            logger.error("模板下载异常", e);
            try {
                response.reset();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            } catch (IOException ignored) {}
        }
    }
    
    /**
     * 导入钥匙组数据
     */
    @RequiresPermissions("service:MechanicalLock:add")
    @Log(title = "钥匙组管理", businessType = BusinessType.IMPORT)
    @PostMapping("/execlImport")
    public AjaxResult execlImport(MultipartFile file, boolean updateSupport) {
        try {
            logger.info("开始导入钥匙组数据");
            
            if (file == null || file.isEmpty()) {
                logger.warn("上传文件为空");
                return AjaxResult.error("上传文件不能为空");
            }
            
            logger.info("文件名: {}, 文件大小: {}", file.getOriginalFilename(), file.getSize());
            
            // 创建ExcelUtil实例
            ExcelUtil<MechanicalLock> util = new ExcelUtil<MechanicalLock>(MechanicalLock.class);
            
            // 解析Excel文件
            List<MechanicalLock> mechanicalLockList = util.importExcel(file.getInputStream());
            
            // 添加调试信息
            logger.info("解析后的数据条数: {}", mechanicalLockList != null ? mechanicalLockList.size() : "null");
            
            if (mechanicalLockList == null) {
                logger.warn("解析后的数据为null");
                return AjaxResult.error("导入数据解析失败，请检查Excel文件格式");
            }
            
            if (mechanicalLockList.isEmpty()) {
                logger.warn("解析后的数据为空列表");
                return AjaxResult.error("导入数据为空，请检查Excel文件是否包含数据");
            }
            
            // 设置创建人
            for (MechanicalLock mechanicalLock : mechanicalLockList) {
                mechanicalLock.setCreateBy(SecurityUtils.getUsername());
            }
            
            return toAjax(mechanicalLockService.batchInsertMechanicalLock(mechanicalLockList));
        } catch (Exception e) {
            logger.error("导入钥匙组数据失败: ", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}
